package com.accp.ssmoa.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.accp.ssmoa.pojo.Role;
import com.accp.ssmoa.pojo.User;
import com.accp.ssmoa.pojo.UserAndRoleKey;
import com.accp.ssmoa.service.DepartmentService;
import com.accp.ssmoa.service.RoleService;
import com.accp.ssmoa.service.UserRoleService;
import com.accp.ssmoa.service.UserService;
import com.accp.ssmoa.util.EncryptingByMD5;
import com.alibaba.fastjson.JSONObject;

@Controller
@Scope("prototype")
@RequestMapping("/admin/user")
public class UserController {

	
	@Resource(name="userServiceImpl")
	private UserService userService;
	
    @Resource(name="departmentServiceImpl")
    private DepartmentService departmentService;
    
    @Resource(name="userRoleServiceImpl")
    private UserRoleService userRoleService;
	
    @Resource(name="roleMapperServiceImpl")
    private RoleService roleService;    
    
	//分页显示数据
	@RequestMapping(value="/listData", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> listData(@RequestBody JSONObject jsonObj){
		
		Map<String, Object> result=new HashMap<String, Object>();
		
		
		//取出前台传过来的封装在json格式里面的数据
		Integer startRow=jsonObj.getIntValue("startRow");//开始行数
		Integer pageSize=jsonObj.getIntValue("pageSize");//每页显示数据数
		
		Integer departmentId=null;
		
		if(!jsonObj.getString("departmentId").equalsIgnoreCase("")) {
			departmentId=jsonObj.getIntValue("departmentId");//部门ID
		}

		//总数据数
		int totalSize=userService.getTotalsize(departmentId);
				
		List<User> users= userService.getPageUser(startRow, pageSize, departmentId);
		
		result.put("total", totalSize);
		result.put("rows", users);
		
		return result;
	}


	//验证用户名是否可用
	@RequestMapping("/validUsername")
	@ResponseBody
	public Map<String, Boolean> validUsername(@RequestParam("username") String username){
		
		Map<String, Boolean>  result=new HashMap<String, Boolean>();
		
		
		User user=userService.getUserByName(username);
		
		
		if(user==null) {
			
			result.put("valid", true);
		}else {
			result.put("valid", false);
		}
		
		return result;
	}

	
	
	//实现添加和修改
	@RequestMapping("/saveOrUpdate")
	@ResponseBody
	public Map<String,Boolean> saveOrUpdate(@ModelAttribute("User") User user,
			HttpServletRequest request) {
		
		Map<String,Boolean> result=new HashMap<String, Boolean>();
		
		int a;//添加或保存持久化操作后的返回值
		String opreate= (String)request.getParameter("opreate");//判断操作
		
		
		//判断是进行修改还是添加
		if(opreate.equalsIgnoreCase("修改用户")) {
			
			if(user.getPassword().equalsIgnoreCase("")) {
				
				user.setPassword(null);
			}else {
				user.setPassword(EncryptingByMD5.encrypting(user.getPassword(), user.getUsername()));
			}
			
			
			a=userService.update(user);
		}else{
			
			user.setPassword(EncryptingByMD5.encrypting(user.getPassword(), user.getUsername()));
			a=userService.save(user);
		}
		
		if(a>0) {
			result.put("success", true);
		}else {
			result.put("success", false);
		}
		
		return result; 
		
	}



	
	/**
	 * 实现授权
	 * @return
	 */
	@RequestMapping("/giveUserRole")
	@ResponseBody
	public Map<String,Boolean> giveUserRole(@RequestParam("userid")Integer userid,
			@RequestParam(value = "roleIds[]") String[] roleIds) {
		
		Map<String,Boolean> result=new HashMap<String, Boolean>();
		
		List<UserAndRoleKey> userRoles=new ArrayList<UserAndRoleKey>();
		
		UserAndRoleKey userRole;
		
		for (String idString : roleIds) {

			userRole=new UserAndRoleKey();
			userRole.setUserId(userid);
			userRole.setRoleId(Integer.parseInt(idString));
			
			userRoles.add(userRole);
		}
		
		//先删除角色所有权限
		userRoleService.deleteByUserId(userid);
		
		//批量增加为角色选择的权限
		int a=userRoleService.insertByList(userRoles);
		
		//根据批量新增返回受影响的数据条数来判断操作是否成功
		if(a>0) {
			result.put("success", true);
		}else {
			result.put("success", false);
		}
		
		
		return result;
	}
	
	
    //显示角色信息树形图
	@RequestMapping("/getAllRoleTreeNode")
	@ResponseBody
	public  List<Object>  getAllRoleTreeNode(){
		
		List<Object> roleTree=roleService.getRoleTree();
		
		
		return roleTree;
	}
	
	
    //根据用户id获取已有角色
	@RequestMapping("/getAllRoleByUserid")
	@ResponseBody
	public  List<Role>  getAllRoleByUserid(@RequestParam("userid")Integer userid){
		
		List<Role> roles=roleService.getRolesByUserid(userid);
		
		
		return roles;
	}
	
	
	
	
	/*需要进行权限控制的操作，增删改以及授权*/
	
	//提供添加用户信息页面
	@RequestMapping("/save")
	public String save(HttpServletRequest request) {

		
		//存储面包屑导航的值进request作用域
		request.setAttribute("pageTitle","用户管理");
		request.setAttribute("url","/admin/user/getListPage");	
		request.setAttribute("nowBread","添加新用户");

		return "user/save";
	}
	
	//实现删除
	@RequestMapping(value="/delete")
	@ResponseBody
	public Map<String,Object> delete(@RequestParam(value = "idsArr[]") String[] idsAttr){
		
		Map<String,Object> result=new HashMap<String, Object>();
		List<Integer> ids=new ArrayList<Integer>();
		
		
		for (String idString : idsAttr) {

			ids.add(Integer.parseInt(idString));
		}

		int a=0;
		
		a=userService.delete(ids);
		
		if(a>0) {
			result.put("success", true);
			result.put("message", "删除成功");
		}else {
			result.put("success", false);
			result.put("message", "删除失败");
		}
		
		return result; 
		
	}
	
	//提供修改用户信息页面
	@RequestMapping("/update")
	public String update(HttpServletRequest request) {

		//存储面包屑导航的值进request作用域
		request.setAttribute("pageTitle","用户管理");
		request.setAttribute("url","/admin/user/getListPage");


		request.setAttribute("nowBread","修改用户");
			
		Integer id=Integer.parseInt(request.getParameter("id"));
						
		//根据id查询机构信息
		User user=userService.getUserById(id);
		request.setAttribute("user", user);

		
		return "user/update";
	}

	//获取弹出选择角色的树形图
	@RequestMapping("/getGiveUserRolePage")
    public String getGiveUserRolePage(@RequestParam("userid")Integer userid,
    		HttpServletRequest request){
		
		request.setAttribute("userid", userid);
		
		
    	return ("user/giveUserRole");
    }
	
	
	
	//初始化用户信息页面
	@RequestMapping("/getListPage")
	public String getUserList(HttpServletRequest request){
		
		//存储面包屑导航的值进request作用域
		request.setAttribute("pageTitle","用户管理");
		
		request.setAttribute("url","/admin/user/getListPage");
		
		request.setAttribute("nowBread","管理");
		
		return "user/list";
	}
	
}
	
	

